<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="deviceGroupLoading = true;"
        >
          设备分组
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键id" align="center" prop="id"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="供应商" align="center" prop="supplierName"/>
      <el-table-column
        label="设备组" align="center" prop="groupId"
        :formatter="row=>formatDeviceGroup(row)"/>
      <el-table-column label="品牌" align="center" prop="brand"/>
      <el-table-column label="型号" align="center" prop="model"/>
      <el-table-column label="设备规格" align="center" prop="specification"/>
      <el-table-column
        label="是否特种设备" align="center" prop="isSpecialEquipment"
        :formatter="row => logicDictFormatter(row.isSpecialEquipment)"/>
      <el-table-column label="使用描述" align="center" prop="useDescribe"/>
      <el-table-column
        label="是否需要检修" align="center" prop="isNeedRepair"
        :formatter="row => logicDictFormatter(row.isNeedRepair)"/>
      <el-table-column label="检修周期" align="center" prop="repairCycle"/>
      <el-table-column label="检修许可证" align="center" prop="repairPermitCard"/>
      <el-table-column label="检修原因" align="center" prop="repairReason"/>
      <el-table-column
        label="是否需要维护" align="center" prop="isNeedMaintain"
        :formatter="row => logicDictFormatter(row.isNeedMaintain)"/>
      <el-table-column label="维护周期" align="center" prop="maintainCycle"/>
      <el-table-column
        label="是否需要计量" align="center" prop="isNeedFitMetering"
        :formatter="row => logicDictFormatter(row.isNeedFitMetering)"/>
      <el-table-column label="计量周期" align="center" prop="fitMeteringCycle"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" min-width="200px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <router-link :to="'/basic_conf/device_conf/instance?deviceId=' + scope.row.id">
            <el-button
              link
              type="primary"
            >
              设备实例
            </el-button>
          </router-link>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DeviceForm ref="formRef" @success="getList"/>
  <el-dialog
    title="设备分组"
    v-model="deviceGroupLoading"
    :before-close="deviceGroupHandleClose"
  >
    <div class="flex gap-2 pt-2">
      <el-tag
        v-for="tag in deviceGroups"
        :key="tag.id"
        closable
        :disable-transitions="false"
        @close="delTag(tag.id)"
      >
        {{ tag.name }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        style="width: 78px"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button v-else class="button-new-tag" size="small" @click="showInput">
        新增设备分组
      </el-button>
    </div>
    <template #footer>
      <el-button @click="deviceGroupLoading = false">取 消</el-button>
    </template>
  </el-dialog>


</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime';
import {DeviceApi, DeviceVO} from '@/api/zjyj/device';
import DeviceForm from './DeviceForm.vue';
import {DICT_TYPE} from '@/utils/dict';
import {dictFormatterStrKey, logicDictFormatter} from '@/utils/formatter';
import {InputInstance} from 'element-plus';
import {DeviceGroupVO, ZjyjDeviceGroupApi} from '@/api/zjyj/devicegroup';
import router from '@/router';

/** 设备 列表 */
defineOptions({name: 'Device'});

const message = useMessage(); // 消息弹窗
const {t} = useI18n(); // 国际化

const loading = ref(true); // 列表的加载中
const list = ref<DeviceVO[]>([]); // 列表的数据
const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  name: undefined,
  supplierId: undefined,
  groupId: undefined,
  brand: undefined,
  model: undefined,
  specification: undefined,
  isSpecialEquipment: undefined,
  useDescribe: undefined,
  isNeedRepair: undefined,
  repairCycle: undefined,
  repairPermitCard: undefined,
  repairReason: undefined,
  isNeedMaintain: undefined,
  maintainCycle: undefined,
  isNeedFitMetering: undefined,
  fitMeteringCycle: undefined
});
const queryFormRef = ref(); // 搜索的表单
const deviceGroupLoading = ref(false); // 设备分组的加载中
/** 查询列表 */

const deviceGroups = ref([]);
/** 导出按钮操作 */
const deviceGroupHandleClose = () => {
  deviceGroupLoading.value = false;
};

const delTag = (tagId) => {
  ZjyjDeviceGroupApi.deleteDeviceGroup(tagId).then(_res => {
    message.success(t('common.delSuccess'));
    deviceGroups.value = deviceGroups.value.filter((item) => item.id !== tagId);
  });
};
const handleInputConfirm = () => {
  const data = {'name': inputValue.value, 'sort': 1} as unknown as DeviceGroupVO;
  ZjyjDeviceGroupApi.createDeviceGroup(data).then(_res => {
    message.success(t('common.createSuccess'));
    getDeviceGroup();
  })
  inputVisible.value = false;
  inputValue.value = '';
};
const InputRef = ref<InputInstance>();

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const inputVisible = ref(false);

const inputValue = ref('');

const getList = async () => {
  loading.value = true;
  try {
    const data = await DeviceApi.getDevicePage(queryParams);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

const formatDeviceGroup = (row) => {
  console.log(row.groupId,deviceGroups.value)
  const data = deviceGroups.value.find(item => item.id === row.groupId);

  return data.name
}

/** 添加/修改操作 */
const formRef = ref();
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id);
};

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm();
    // 发起删除
    await DeviceApi.deleteDevice(id);
    message.success(t('common.delSuccess'));
    // 刷新列表
    await getList();
  } catch {
  }
};

const getDeviceGroup = async () => {
  const groupData = await ZjyjDeviceGroupApi.getDeviceGroupPage({page: 1, pageSize: 9999})
  deviceGroups.value = groupData.list
}

/** 初始化 **/
onMounted(() => {
  getList();
  getDeviceGroup();
});
</script>
